<template>
  <div id="video-detail" class="ptop-20">
    <div class="left-video">
      <div class="font-weight">
        <a-icon type="left" />
        {{ showFocus ? '视频详情' : 'MV详情' }}
      </div>
      <!-- 视频播放 -->
      <video-player
        ref="myVideo"
        :options="options"
        @next="changeNextVideo"
        @loopNextVideo="changeNextVideo"
        @reloadinterface="getVideoUrl" />
      <!-- <div class="info"> -->
        <!-- 用户信息 -->
        <div class="user-info">
          <img class="pointer" @click="goUserDetail" v-lazy="avatar">
          <span class="mleft-10 pointer">
            {{ avatarName }}
          </span>
          <!-- <a-button v-show="showFocus" class="mright-10 br-30 play-all" @click="follow">
            {{ isFollow ? '已关注' : '关注' }}
            <a-icon class="font-16" :type="isFollow ? 'check' : 'plus'" />
          </a-button> -->
        </div>
        <!-- 视频信息 -->
        <div class="video-info">
          <div class="font-18 font-weight">
            {{ title }}
          </div>
          <div class="font-12 mtop-5">
            {{ describe }}
          </div>
          <div class="font-12 mtop-10" style="color: rgb(207, 207, 207);">
            <span>发布时间: {{ publishtime }}</span>
            <span class="mleft-20">播放次数: {{ playTime }}</span>
          </div>
        </div>
        <ul>
          <li
            v-for="item in videoInfo.videoGroup"
            :key="item.id"
            class="tag-item mright-10 mtop-5">{{ item.name }}</li>
        </ul>
        <div class="btn">
          <a-button class="mright-10 br-30" @click="changeLiked">
            <a-icon
              class="font-16"
              type="like"
              :class="{ 'isLiked': isLiked }"
              :theme="isLiked ? 'filled' : 'outlined'"
            />
            {{ isLiked ? '已赞' : '赞' }}({{ shareInfo.likedCount }})
          </a-button>
          <a-button class="mright-10 br-30" @click="subOne">
            <a-icon class="font-16" :type="subShow ? 'folder-add' : 'check'" />
            收藏({{ videoInfo.subscribeCount || videoInfo.subCount }})
          </a-button>
          <!-- <a-button class="mright-10 br-30 play-all" @click="subOne(0)" v-show="!subShow">
            <a-icon class="font-16" type="check" />
            已收藏(88)
          </a-button> -->
          <a-button class="br-30">
            <a-icon class="font-16" type="logout" :rotate="-45" />
            分享({{ shareInfo.shareCount }})
          </a-button>
        </div>
        <!-- 评论组件 -->
        <Discuss
          ref="discuss"
          :newTotal="total"
          :newComments="comment"
          @scrollTo.passive="scroll"
        />
      </div>
    <!-- </div> -->
    <div class="related-recomm">
      <div class="related-title font-weight">
        相关推荐
        <div class="change-related" @click="getRelatedVideo">
          换一批<a-icon type="sync" />
        </div>
      </div>
      <mv-list
        v-for="item in relatedList"
        :key="item.vid"
        :playcount="item.playTime"
        :cover="item.coverUrl"
        :videoAuthor="item.creator"
        :videoTitle="item.title"
        :durationms="item.durationms"
        :mvStyle="{
          width: '100%',
          display: 'grid',
          'grid-gap': '10px',
          'grid-template-columns': '55% 45%',
        }"
        @goDetail="event => goDetail(event, item.vid)"
      ></mv-list>
    </div>
  </div>
</template>

<script>
// import { mapState } from 'vuex';
import { relatedVideo, videoPlayUrl, mvPlayUrl } from '@/api/music';
import { likeResource, subVideo, subMV } from '@/api';
import {
  videoComment,
  videoDetail,
  mvDetail,
  videoShare,
  mvShare,
  mvComment
} from '@/api/detail';
import { changeBigCount,changeTimeStamp, checkoutType } from '@/utils/figure';
import VideoPlayer from '@/components/Player/VideoPlayer';
import Discuss from '@/components/Detail/Discuss';
import MvList from '@/components/Content/MvList';

// const AsyncMudoles = this.defineAsyncComponent({
//   MvList,
//   Discuss,
//   delay: 1000,
//   suspensible: true
// })

export default {
  name: 'videoDetail',

  components: {
    // AsyncMudoles,
    MvList,
    Discuss,
    VideoPlayer
  },

  data() {
    return {
      // 相关视频列表
      relatedList: [],
      // playerOptions: {
      //   height: '360',
      //   autoplay: true,
      //   muted: false,
      //   language: 'en',
      //   // 可选的播放速度
      //   playbackRates: [0.5, 1.0, 1.5, 2.0, 3.0],
      //   sources: [{
      //     type: "video/mp4",
      //     // mp4
      //     src: "http://vjs.zencdn.net/v/oceans.mp4",
      //     // webm
      //     // src: "https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm"
      //   }],
      //   poster: "https://surmon-china.github.io/vue-quill-editor/static/images/surmon-1.jpg",
      // },
      // 评论参数
      params: {
        id: '',
        limit: 20,
        offset: 0,
        // before: 0,
        timestamp: new Date().getTime()
      },
      // 评论列表
      comment: [],
      // 评论数
      total: 0,
      // 视频信息
      videoInfo: {},
      // 点赞转发数
      shareInfo: {},
      // 用户头像
      avatar: '',
      // 显示关注按钮,只有视频才有关注
      showFocus: true,
      // isFollow: false,
      // 点赞/未点赞
      isLiked: false,
      // 显示收藏或已收藏按钮
      subShow: true,
      nextIndex: -1,
      // video配置
      options: {
        sources: [{
          type: "video/mp4",
          // mp4
          src: ""
          // webm
          // src: "https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm"
        }],
        poster: ""
      }
    }
  },

  computed: {
    player() {
      return this.$refs.myVideo.$refs.videoPlayer;
    },
    getDiscuss() {
      return this.$refs.discuss;
    },
    // 判断是mv还是video
    getQuery() {
      return this.$route.query;
    },
    // 播放次数
    playTime() {
      if (this.videoInfo && this.videoInfo.playTime) {
        return changeBigCount(this.videoInfo.playTime);
      }
      return changeBigCount(this.videoInfo.playCount);
    },
    // 用户名
    avatarName() {
      if (this.videoInfo && this.videoInfo.creator) {
        return this.videoInfo.creator.nickname;
      }
      return this.videoInfo.artistName;
    },
    // 视频标题
    title() {
      if (this.videoInfo && this.videoInfo.title) {
        return this.videoInfo.title;
      }
      return this.videoInfo.name;
    },
    // 视频介绍
    describe() {
      if (this.videoInfo && this.videoInfo.description) {
        return this.videoInfo.description;
      }
      return this.videoInfo.desc
    },
    publishtime() {
      return changeTimeStamp(this.videoInfo.publishTime);
    }
    // ...mapState({
    //   videoInfo: state => state.detail.videoInfo
    // })
  },

  watch: {
    '$route.query': {
      handler(value) {
        const { vid, mid } = value;
        if (vid) {
          this.showFocus = true;
          this.params.id = vid;
          this.$nextTick(() => {
            this.getDiscuss.params.type = 5;
            this.getDiscuss.params.id = vid;
            this.getDiscuss.getHotComments();
          })
        } else {
          this.showFocus = false;
          this.params.id = mid;
          this.$nextTick(() => {
            this.getDiscuss.params.type = 1;
            this.getDiscuss.params.id = mid;
            this.getDiscuss.getHotComments();
          })
        }
        
        this.getVideoUrl();
        this.getVideoDetail();
        // this.getRelatedVideo();
        this.getVideoShare();
        this.getVideoComment();
      },
      immediate: true
    }
  },

  methods: {
    // 获取相关视频
    async getRelatedVideo() {
      const id = this.getQuery.vid || this.getQuery.mid;
      const res = (await relatedVideo(id)).data;
      this.relatedList = Object.freeze(res.data);
    },
    async getVideoComment() {
      let res = null;
      if (this.getQuery.vid) {
        this.params.id = this.getQuery.vid;
        res = (await videoComment(this.params)).data; 
      } else {
        this.params.id = this.getQuery.mid;
        res = (await mvComment(this.params)).data;
      }
      this.comment = Object.freeze(res.comments);
      this.total = res.total;
    },
    // 获取视频详情
    async getVideoDetail() {
      let res = null;
      if (this.getQuery.vid) {
        res = (await videoDetail(this.getQuery.vid)).data;
        this.avatar = res.data.creator.avatarUrl;
        // 是否关注视频作者
        this.isFollow = res.data.creator.followed;
      } else {
        res = (await mvDetail(this.getQuery.mid)).data;
        this.avatar = res.data.artists[0].img1v1Url;
      }
      this.videoInfo = Object.freeze(res.data);
      // 封面
      this.options.poster = res.data.coverUrl;
      this.options.height = res.data.height;
    },
    // 获取视频点赞转发
    async getVideoShare() {
      let res = null;
      if (this.getQuery.vid) {
        res = (await videoShare(this.getQuery.vid)).data;
      } else {
        res = (await mvShare(this.getQuery.mid)).data;
      }
      this.shareInfo = res;
      this.isLiked = this.shareInfo.liked;
    },
    // 获取视频播放地址
    async getVideoUrl() {
      // let res = null;
      if (this.getQuery.vid) {
        const res = (await videoPlayUrl(this.getQuery.vid)).data;
        // if (this.player.src !== res.urls[0].url) {
        //   this.player.src = res.urls[0].url;
        //   this.player.load();
        //   return;
        // }
        this.options.sources = [
          {
            type: 'video/mp4',
            src: res.urls[0].url
          }
        ];
        // if (res.code === 200) {
          // if (!this.player.isControlBar && 
          //   this.player.showError) {
        this.player.isControlBar = true;
        this.player.showError = false;
          // }
        // } else {}
        if (this.player) {
          this.player.pause();
          this.player.src = res.urls[0].url;
          this.player.load();
          this.player.play();
        }
        // this.isPlay(res.code, res.urls[0].urls);
      } else {
        const res = (await mvPlayUrl(this.getQuery.mid)).data;
        this.options.sources = [
          {
            type: 'video/mp4',
            src: res.data.url
          }
        ];
        if (res.code === 200) {
          if (!this.player.isControlBar && 
            this.player.showError) {
            this.player.isControlBar = true;
            this.player.showError = false;
          }
        } else {}
        if (this.player) {
          this.player.pause && this.player.pause();
          this.player.src = res.data.url;
          this.player.load && this.player.load();
          this.player.play && this.player.play();
        }
      }
    },
    // isPlay(code, url) {
    //   if (code === 200) {
    //     // if (!this.player.isControlBar && 
    //     //   this.player.showError) {
    //       this.player.isControlBar = true;
    //       this.player.showError = false;
    //     // }
    //   } else {}
    //   if (this.player) {
    //     this.player.pause();
    //     this.player.src = url;
    //     this.player.load();
    //     this.player.play();
    //   }
    // },
    async changeLiked() {
      this.isLiked = !this.isLiked;
      if (this.isLiked) {
        this.shareInfo.likedCount++;
      } else {
        this.shareInfo.likedCount--;
      }
      const res = (await likeResource({
        type: this.$route.query.vid ? 5 : 1,
        t: this.isLiked ? 1: 0,
        id: this.$route.query.vid ? this.$route.query.vid : this.$route.query.mid
      })).data;
      if (res.code === 200) {
        this.$message.success('点赞成功');
      }
    },
    goUserDetail() {
      const query = this.$route.query;
      if (query.vid) {
        this.$router.push({
          name: 'userdetail',
          query: {
            id: this.videoInfo.creator.userId
          }
        })
      } else {
        this.$router.push({
          name: 'artistdetail',
          query: {
            id: this.videoInfo.artists[0].id
          }
        })
      }
    },
    goDetail(event, id) {
      const type = isNaN(Number(id));
      if (type) {
        this.$router.push({
          name: 'videodetail',
          query: {
            vid: id
          }
        })
      } else {
        this.$router.push({
          name: 'videodetail',
          query: {
            mid: id
          }
        })
      }
      // 点击的时候需要改变nextIndex
      this.nextIndex = this.relatedList.findIndex(item => item.vid === id);
    },
    // 播放下一个视频
    changeNextVideo() {
      if (this.nextIndex === this.relatedList.length - 1) {
        this.getRelatedVideo();
        this.nextIndex = -1;
        this.$message.success('已为你更新相关视频！');
      }
      const id = this.relatedList[++this.nextIndex].vid;
      this.goDetail(null, id);
    },
    // 关注/取消关注用户
    // async follow() {
    //   this.isFollow = !this.isFollow;
    //   const res = (await followUser({
    //     id: this.videoInfo.creator.userId,
    //     t: this.isFollow ?  1 : 0
    //   })).data;
    //   console.log(res);
    // },
    // 点击分页后，滚动回最新评论标题处
    scroll(current) {
      this.params.offset = (current - 1) * this.params.limit;
      this.getVideoComment();
      const detail = document.querySelector('#video-detail');
      const lastDOM = this.$refs.discuss.$el.childNodes;
      detail.scrollTo({
        left: 0,
        top: lastDOM[lastDOM.length - 1].lastChild.offsetTop - 95,
        behavior: 'smooth'
      })
    },
    subOne() {},
  },

  created() {
    this.getRelatedVideo();
    // 刷新前将video信息存放到sessionStorage中,避免刷新数据丢失
    // window.addEventListener('beforeunload', () => {
    //   sessionStorage.setItem('currentVideo', JSON.stringify(this.videoInfo));
    // });
    // this.getVideoDetail();
    // const video = JSON.parse(sessionStorage.getItem('currentVideo'));
    // if (video && Object.keys(video).length) {
    //   this.$store.commit('detail/VIDEOINFO', video);
    // }
  }
}
</script>

<style lang="less" scoped>
#video-detail {
  display: grid;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  justify-content: center;
  grid-column-gap: 20px;
  grid-template-columns: 60% 25%;
  .left-video {
    display: grid;
    grid-row-gap: 15px;
    .user-info {
      position: relative;
      display: flex;
      align-items: center;
      >img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
      }
      .play-all {
        position: absolute;
        right: 0;
      }
    }
    >ul {
      display: flex;
      flex-wrap: wrap;
      .tag-item {
        // width: 36px;
        height: 22px;
        background-color: #f7f7f7;
        color: #363636;
        font-size: 12px;
        border-radius: 10px;
        text-align: center;
        line-height: 22px;
        padding: 0 10px;
      }
    }
    .isLiked {
      color: #ec4141;
    }
  }
  .related-recomm {
    .related-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  /deep/.video-title {
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    white-space: normal;
    text-overflow: unset;
    overflow: hidden;
  }
}
</style>